import { Module } from 'vuex';
import { ILoginState } from './types';
import {
  accountLoginRequset,
  userInfoRequest,
  menusRequest
} from '@/service/login/login';
import localStroage from '@/common/cache';
import router from '@/router';
const accountLogin: Module<ILoginState, any> = {
  namespaced: true,
  state: {
    token: '',
    userInfo: [],
    userMenus: []
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changeMenus(state, userMenus: any) {
      state.userMenus = userMenus;
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload) {
      //登录请求
      const { data } = await accountLoginRequset(payload);
      commit('changeToken', data.token);
      localStroage.setItem('token', data.token);
      //用户信息请求
      const userInfo = await userInfoRequest(data.id);
      commit('changeUserInfo', userInfo.data);
      localStroage.setItem('userInfo', userInfo.data);
      //菜单请求
      const { id } = userInfo.data.role;
      const menuInfo = await menusRequest(id);
      commit('changeMenus', menuInfo.data);
      localStroage.setItem('menus', menuInfo.data);
      //跳转
      router.push('/home');
    }
  }
};

export default accountLogin;
